package com.fdhwws.web.filter;

import com.fdhwws.web.domain.User;
import com.fdhwws.web.service.UserService;
import com.fdhwws.web.service.impl.UserServiceImpl;
import com.fdhwws.web.util.CookieUtil;
import com.fdhwws.web.util.InfoSecurityUtil;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class AuthenticationFilter implements Filter {
    private final UserService userService = new UserServiceImpl();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        System.out.println("访问路径: " + requestURI);
        User loginUser = null;
        try {
            //尝试从请求中解析出用户
            String uid = CookieUtil.getCookie(request, "uid");
            if (!StringUtils.isNullOrEmpty(uid)) {
                String decrypt = InfoSecurityUtil.decrypt(uid); // 解密uid
                loginUser = userService.getUserById(Integer.parseInt(decrypt)); // 根据解密的uid获取用户信息
                if (loginUser != null && loginUser.getValid()) {
                    request.setAttribute("user", loginUser);
                }
            }
        } catch (Exception e) {
            System.out.println("uid异常");
            CookieUtil.deleteCookie(response, "uid");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
